'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.genPromiseWithTimeout = exports.promiseTimeout = exports.isTimeout = exports.TimeoutError = undefined;

var _promiseDelay = require('./promiseDelay');

var _promiseDelay2 = _interopRequireDefault(_promiseDelay);

var _isPromise = require('./isPromise');

var _isPromise2 = _interopRequireDefault(_isPromise);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TimeoutError = exports.TimeoutError = {
    message: 'timeout'
};
var isTimeout = exports.isTimeout = function isTimeout(res) {
    return res === TimeoutError;
};
var promiseTimeout = exports.promiseTimeout = function promiseTimeout(promise) {
    var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;

    var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
        _ref$isReject = _ref.isReject,
        isReject = _ref$isReject === undefined ? true : _ref$isReject,
        _ref$result = _ref.result,
        result = _ref$result === undefined ? TimeoutError : _ref$result;

    var _promise = (0, _isPromise2.default)(promise) ? promise : new Promise(promise);
    var wait = (0, _promiseDelay2.default)(timeout).then(function () {
        return Promise[isReject ? 'reject' : 'resolve'](result);
    });
    return Promise.race([_promise, wait]);
};

var genPromiseWithTimeout = exports.genPromiseWithTimeout = function genPromiseWithTimeout(runner) {
    var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3000;
    var defResult = arguments[2];
    var isReject = arguments[3];

    var task = new Promise(function (resolve, reject) {
        runner(resolve, reject);
    });
    return promiseTimeout(task, timeout, {
        isReject: isReject,
        defResult: defResult
    });
};

exports.default = promiseTimeout;